package com.biwu.JSON;

import cn.hutool.json.JSONUtil;
import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 王俊彪
 * @version 1.0
 */
public class JsonTest {
    @Test
    public void testObjectToJson(){
        Student student = new Student(12356, "jack", "男", 18);
        String stuJson = JSONUtil.toJsonStr(student);
        System.out.println(stuJson);
    }
    @Test
    public void testJsonToObject(){
        String stuJson ="{\"sno\":12356,\"sname\":\"jack\",\"gender\":\"男\",\"age\":18}";
        String stu02Json = "{'sno':12356,'sname':'jack','gender':'男','age':18}";
        Student student = JSONUtil.toBean(stuJson, Student.class);
        Student student02 = JSONUtil.toBean(stuJson, Student.class);
        System.out.println(student);
        System.out.println(student02);
    }
    @Test
    //将一个集合转换成JSON
    public void testListToJson(){
        List<Student> students = Arrays.asList(new Student(12356, "jack", "男", 18),
                new Student(12356, "mary", "女", 18));
        String jsonStr = JSONUtil.toJsonStr(students);
        System.out.println(jsonStr);
        System.out.println(JSONUtil.toJsonPrettyStr(students));

    }
    @Test
    public void testJsonPrettyStr(){
        String students="[{\"sno\":12356,\"sname\":\"jack\",\"gender\":\"男\",\"age\":18},{\"sno\":12356,\"sname\":\"mary\",\"gender\":\"女\",\"age\":18}]\n";
        JSONUtil.parseArray(students).toList(Student.class).forEach(System.out::println);
    }
    @Test
    public void testMapToJson(){
        Map<String, Student> stuMap = new HashMap<>();
        stuMap.put("123456",new Student(12356, "jack", "男", 18));
        stuMap.put("123457",new Student(12356, "mary", "女", 20));
        String jsonStr = JSONUtil.toJsonPrettyStr(stuMap);
        System.out.println(jsonStr);
    }
}
